package xyf.p01.array_nodelist;

import commons.ListNode;

/**
 * ClassName: P0002_AddTwoNumbers
 * Description:
 * Author: xyf
 * Date: 9/2/22 11:49 PM
 * Version: 1.0
 **/
public class P0002_AddTwoNumbers
{
    public ListNode addTwoNumbers(ListNode l1, ListNode l2)
    {
        int last = 0;
        ListNode head = null;
        ListNode tail = null;
        while (l1 != null || l2 != null)
        {
            int num1 = 0;
            if (l1 != null)
            {
                num1 = l1.val;
            }
            int num2 = 0;
            if (l2 != null)
            {
                num2 = l2.val;
            }
            int sum = num1 + num2 + last;
            if (sum >= 10)
            {
                last = 1;
            }
            else
            {
                last = 0;
            }
            sum = sum % 10;

            ListNode curNode = new ListNode(sum);
            if (head == null)
            {
                head = curNode;
                tail = curNode;
            }
            else
            {
                tail.next = curNode;
                tail = tail.next;
            }
            if (l1 != null)
            {
                l1 = l1.next;
            }
            if (l2 != null)
            {
                l2 = l2.next;
            }
        }

        if (last == 1)
        {
            ListNode curNode = new ListNode(1);
            tail.next = curNode;
        }

        return head;
    }
}
